package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.obrempon.credit.market.R
import com.obrempon.credit.market.base.app.ObremponActivityStackManager
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponOrderDetailsActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.adapter.ObremponOrderDetailsWalletApt
import com.obrempon.credit.market.ui.dialog.ObremponUserDataClearDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountAddDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountBindOtherDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountDeleteDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountOrderDetailsOnlyOneDialog
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.credit.market.utils.helper.ObremponProductHelper
import com.obrempon.credit.market.utils.helper.ObremponProductStatusHelper
import com.obrempon.credit.market.utils.helper.ObremponScoreDialogHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.math.BigDecimal

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/19 10:57
 * @Annotation：订单详情
 */
class ObremponOrderDetailsAct: CommonActivity() {
    lateinit var binding: ObremponOrderDetailsActBinding
    private var deleteDataAfterDate = ""
    private var eventRemark = ""
    private var walletAdapter: ObremponOrderDetailsWalletApt? = null

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context,pName: String, pToken: String) {
            val intent = Intent(context, ObremponOrderDetailsAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun takeObremponRootView(): View {
        binding = ObremponOrderDetailsActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitleVisibility(View.GONE)
        setObremponBackBtnRes(R.mipmap.obrempon_back_white_icon)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))
        initOrderDetailsRefrashView()
        initOrderDetailsAccountRecyclerView()
        binding.orderDetailsLayout.visibility = View.INVISIBLE
        binding.buttonDeleteData.visibility = View.INVISIBLE

        binding.orderStatusTipsLayout.visibility = View.GONE
        binding.disbursingFrenchTipsLayout.visibility = View.GONE
        binding.textWalletAccountAddTips.visibility = View.GONE
        binding.walletListView.visibility = View.GONE
        binding.walletAddLayout.visibility = View.GONE
    }

    override fun initObremponListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,takeObremponProductName(),takeObremponProductToken())
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,eventRemark)
        }
        //新增账户
        binding.walletAddLayout.setOnClickListener {
            showObremponWalletAccountAddDialog()
        }
        //删除用户数据
        binding.buttonDeleteData.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_DATA_CLEAR,eventRemark)
            val pList = ObremponProductHelper.takeObremponUncompleteProductList()
            //存在未结清的账单
            if (pList.size > 0){
                showErrorTipsDialog(getString(R.string.obrempon_user_data_clear_error),eventRemark)
                return@setOnClickListener
            }
            showObremponClearDataDialog()
        }
    }

    override fun takeObremponData() {
        showObremponLoading()
        loadObremponOrderDetailsInfoAction()
    }

    /* 初始化刷新 */
    private fun initOrderDetailsRefrashView() {
        binding.orderDetailsRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.orderDetailsRefreshView.setOnRefreshListener {
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
            loadObremponOrderDetailsStatusAction()
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderDetailsAccountRecyclerView(){
        binding.walletListView.isNestedScrollingEnabled = false
        binding.walletListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.walletListView.layoutManager = layoutManager
//        val topDecoration = ObremponDensityUtil.dp2px(12f)
//        binding.walletListView.addItemDecoration(LinearSpacingItemDecoration(0, 0,topDecoration,0))
        walletAdapter = ObremponOrderDetailsWalletApt(binding.walletListView)
        binding.walletListView.adapter = walletAdapter!!
        binding.walletListView.itemAnimator = DefaultItemAnimator()
        walletAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = walletAdapter!!.getItem(position)
            if (childView.id == R.id.imageRemove){
                showObremponWalletAccountDeleteDialog(item)
            }
        }
    }

    /**
     * 获取产品名称
     */
    private fun takeObremponProductName(): String{
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取产品token
     */
    private fun takeObremponProductToken(): String{
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 共用Views
     */
    @SuppressLint("SetTextI18n")
    fun showObremponOrderDetailsViews(obj: JSONObject) {
        binding.textApplyAmount.text = "${BigDecimal(obj.optString("amount")).stripTrailingZeros().toPlainString()} ${obj.optString("currency")}"
        binding.textApplyTerm.text = String.format(getString(R.string.obrempon_order_details_loan_term_days),obj.optString("days"))
        binding.orderDetailsLayout.visibility = View.VISIBLE
    }

    /**
     * 审核中
     */
    fun showObremponOrderDetailsReviewingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.obrempon_credit_reviewing_icon)
        binding.textOrderStatus.text = getString(R.string.obrempon_order_status_in_review)
        binding.textOrderStatus.setTextColor(getColor(R.color.color_ff0569ff))
        binding.textOrderStatusTips.setTextColor(getColor(R.color.color_ffd59b66))
        binding.orderStatusTipsLayout.visibility = View.VISIBLE

        binding.disbursingFrenchTipsLayout.visibility = View.GONE
        binding.walletAddLayout.visibility = View.GONE
        //法语地区才显示添加绑卡账户按钮
        if (ObremponConfigs.isObremponFrench()){
            binding.textWalletAccountAddTips.visibility = View.VISIBLE
            binding.walletAddLayout.visibility = View.VISIBLE
        }

        val showApproveTime = getString(R.string.obrempon_order_details_reviewing_approve_time)
        val showContactTime = getString(R.string.obrempon_order_details_reviewing_contact_time)
        val showTips = String.format(getString(R.string.obrempon_order_details_reviewing_tips),showApproveTime,showContactTime)
        val index1 = showTips.indexOf(showApproveTime)
        val index2 = showTips.indexOf(showContactTime)
        val spString = SpannableString(showTips)
        spString.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff8f28)), index1, index1 + showApproveTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        spString.setSpan(StyleSpan(Typeface.BOLD), index1, index1 + showApproveTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff8f28)), index2, index2 + showContactTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), index2, index2 + showContactTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textOrderStatusTips.text = spString
        binding.buttonDeleteData.visibility = View.INVISIBLE
        //显示收款账户列表
        binding.walletListView.visibility = View.VISIBLE
        loadObremponOrderDetailsWalletListAction()
        loadObremponOrderDetailsScoreCommentAction()
    }

    /**
     * 放款中
     */
    fun showObremponOrderDetailsDisbursingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.obrempon_order_details_status_disbursing_icon)
        binding.textOrderStatus.text = getString(R.string.obrempon_order_status_disbursing)
        binding.textOrderStatus.setTextColor(getColor(R.color.color_ffff8717))
        binding.orderStatusTipsLayout.visibility = View.GONE
        binding.buttonDeleteData.visibility = View.INVISIBLE

        binding.disbursingFrenchTipsLayout.visibility = View.GONE
        binding.walletAddLayout.visibility = View.GONE
        //法语地区才显示添加绑卡账户按钮
        if (ObremponConfigs.isObremponFrench()){
            binding.disbursingFrenchTipsLayout.visibility = View.VISIBLE
            binding.textWalletAccountAddTips.visibility = View.VISIBLE
            binding.walletAddLayout.visibility = View.VISIBLE
        }

        //显示收款账户列表
        binding.walletListView.visibility = View.VISIBLE
        loadObremponOrderDetailsWalletListAction()
        loadObremponOrderDetailsScoreCommentAction()
    }

    /**
     * 已拒绝
     */
    fun showObremponOrderDetailsRejectedViews(obj: JSONObject) {
        binding.imgOrderStatus.setImageResource(R.mipmap.obrempon_order_details_status_rejected_icon)
        binding.textOrderStatus.text = getString(R.string.obrempon_order_status_rejected)
        binding.textOrderStatus.setTextColor(getColor(R.color.color_ffff4d14))
        binding.textOrderStatusTips.setTextColor(getColor(R.color.color_ffd59b66))
        binding.orderStatusTipsLayout.visibility = View.VISIBLE

        var againApplyDate = obj.optString("againApplyDate","")
        if (againApplyDate.isEmpty()){
            againApplyDate = ObremponProcessHelper.takeObremponAuthApplyAgainDate()
        }
        val showTips = String.format(getString(R.string.obrempon_order_details_rejected_tips),againApplyDate)
        val index = showTips.indexOf(againApplyDate)
        val spString = SpannableString(showTips)
        spString.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff8f28)), index, index + againApplyDate.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        spString.setSpan(StyleSpan(Typeface.BOLD), index, index + againApplyDate.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textOrderStatusTips.text = spString

        binding.disbursingFrenchTipsLayout.visibility = View.GONE
        binding.textWalletAccountAddTips.visibility = View.GONE
        binding.walletAddLayout.visibility = View.GONE
        //不显示收款账户
        binding.walletListView.visibility = View.GONE

        //需要判断是否需要显示删除用户数据按钮
        submitObremponUserClearDataAction(true)
    }

    /**
     * 待还款
     */
    fun showObremponOrderDetailsRepayViews() {
        //刷新产品列表
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
        //显示待还款列表
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SHOW_REPAY))
        launch(Dispatchers.Main){
            delay(1000)
            ObremponActivityStackManager.finishAllActivity(ObremponMainAct::class.java)
        }
    }

    fun showObremponOrderDetailsWalletList(walletList: ArrayList<JSONObject>) {
        walletAdapter?.data = walletList

        //法语地区 && 绑卡账户只有一个，需要提示
        if (ObremponConfigs.isObremponFrench() && walletList.size == 1){
            showObremponOrderDetailsWalletOnlyOneDialog()
        }
    }

    /**
     * 法语地区 绑卡账户只有一个提示
     */
    private fun showObremponOrderDetailsWalletOnlyOneDialog(){
        val walletOnlyOneDialog = ObremponWalletAccountOrderDetailsOnlyOneDialog(this,eventRemark,object : ObremponWalletAccountOrderDetailsOnlyOneDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.buttonOrderDetailsWalletAccountAdd -> {//继续添加
                        binding.walletAddLayout.callOnClick()
                    }
                }
            }
        })
        walletOnlyOneDialog.setCancelable(true)
        walletOnlyOneDialog.setCanceledOnTouchOutside(true)
        walletOnlyOneDialog.show()
    }

    /**
     * 清空用户数据dialog
     */
    private fun showObremponClearDataDialog(){
        val clearDialog = ObremponUserDataClearDialog(this,object : ObremponUserDataClearDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                //删除用户数据
                submitObremponUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
        clearDialog.showObremponDeletePersonalDataDesc(ObremponConfigsHelper.takeObremponDeletePersonalDataDesc(),deleteDataAfterDate)
    }

    /**
     * 添加绑卡dialog
     */
    private fun showObremponWalletAccountAddDialog(){
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_ADD,eventRemark)
//        onIntent(ObremponAuthAccountCreateAct::class.java)
        val bindCardDialog = ObremponWalletAccountAddDialog(this,eventRemark,object : ObremponWalletAccountAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                onObremponSumbitAuthStepWalletAddAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个账号
     */
    fun showObremponWalletAccountOtherDialog(otherInfo: JSONObject) {
        val bindOtherDialog = ObremponWalletAccountBindOtherDialog(this,eventRemark,object : ObremponWalletAccountBindOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.buttonWalletOtherConfirm){//添加
                    onObremponSumbitAuthStepWalletAddAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        bindOtherDialog.setCancelable(true)
        bindOtherDialog.setCanceledOnTouchOutside(false)
        bindOtherDialog.show()
        bindOtherDialog.showObremponWalletAccountInfo(otherInfo)
    }

    /**
     * 删除提示
     */
    private fun showObremponWalletAccountDeleteDialog(item: JSONObject){
        item.put("walletLogo",item.optString("logo"))
        item.put("walletDesc",item.optString("name"))
        item.put("walletMobile",item.optString("account"))
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
        val deleteDialog = ObremponWalletAccountDeleteDialog(this,eventRemark, object : ObremponWalletAccountDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletAccountDeleteConfirm){
                    onObremponDeleteWalletAccountAction(item.optString("cardId"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.showObremponWalletAccountInfo(item)
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        //刷新已添加账户列表
        if (event.eventType == ObremponEventData.TYPE.OBREMPON_WALLET_REFRESH){
            loadObremponOrderDetailsInfoAction()
        }
    }

    /**
     * 获取贷款信息
     */
    private fun loadObremponOrderDetailsInfoAction(){
        //刷新产品列表
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_APPLY_PATH)
            put("product",takeObremponProductName())
            put("token",takeObremponProductToken())
        }
        doPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //显示共用View
                    showObremponOrderDetailsViews(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                loadObremponOrderDetailsStatusAction()
            }
        })
    }

    /**
     * 获取产品对应的流程
     * 根据流程接口判断状态
     */
    private fun loadObremponOrderDetailsStatusAction(){
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_PROCESS_PATH)
            put("product",takeObremponProductName())
            put("token",takeObremponProductToken())
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //申请状态
                    val applyStatus = obj.optString("applyStatus","")
                    //订单状态
                    val orderStatus = obj.optString("orderStatus","")

                    val isReviewing = ObremponProductStatusHelper.StatusRepository(applyStatus,orderStatus).isReviewing()
                    val isDisbursing = ObremponProductStatusHelper.StatusRepository(applyStatus,orderStatus).isDisbursing()
                    val isRejected = ObremponProductStatusHelper.StatusRepository(applyStatus,orderStatus).isRejected()
                    val isRepay = ObremponProductStatusHelper.StatusRepository(applyStatus,orderStatus).isRepayNow()

                    //审核中
                    if (isReviewing){
                        obj.put("eventRemark", "Reviewing Page")
                        showObremponOrderDetailsReviewingViews()
                        return
                    }

                    //放款中
                    if (isDisbursing){
                        obj.put("eventRemark", "Disbursing Page")
                        showObremponOrderDetailsDisbursingViews()
                        return
                    }

                    //已拒绝
                    if (isRejected){
                        obj.put("eventRemark", "Rejected Page")
                        showObremponOrderDetailsRejectedViews(obj)
                        return
                    }

                    //待还款
                    showObremponOrderDetailsRepayViews()
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 获取账户列表
     */
    private fun loadObremponOrderDetailsWalletListAction(){
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_LIST_PATH)
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                val walletList = arrayListOf<JSONObject>()

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("showDelete", ObremponConfigs.isObremponFrench())
                        walletList.add(item)
                    }
                }
                showObremponOrderDetailsWalletList(walletList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 只有审核中或放款中需要调此接口
     * 获取评分配置
     */
    private fun loadObremponOrderDetailsScoreCommentAction() {
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_STAR_COMMENT_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    ObremponScoreDialogHelper.showStarDialog(this@ObremponOrderDetailsAct,obj,true)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun submitObremponUserClearDataAction(isShowDeleteButton: Boolean){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_USER_DATA_CLEAR_PATH)
        }
        if (isShowDeleteButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                if (isShowDeleteButton){
                    val obj = data.optJSONObject("obj")
                    if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                        binding.buttonDeleteData.visibility = View.VISIBLE
                        deleteDataAfterDate = obj.optString("againDate")
                    } else {
                        binding.buttonDeleteData.visibility = View.INVISIBLE
                    }
                } else {
                    hideObremponLoading()
                    //退出登录，需要移除用户保存的信息
                    ObremponSharedHelper.onObremponLoginOut()
                    onIntent(ObremponLoginAct::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showObremponToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    private fun onObremponSumbitAuthStepWalletAddAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }

        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadObremponOrderDetailsWalletListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = ObremponConfigsHelper.takeObremponConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        showObremponWalletAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        } else {
                            hideObremponLoading()
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        showObremponToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun onObremponDeleteWalletAccountAction(ids: String) {
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        doPostAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showObremponToast(data.optString("msg"))
                //刷新列表
                loadObremponOrderDetailsWalletListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.orderDetailsRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${takeObremponProductName()} OrderDetails Page"
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_ORDER_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_ORDER_DETAILS_END,eventRemark)
    }
}